package tr.edu.yildiz.ce.dap.appagent.command.deployment.proxy;

import org.osgi.framework.Bundle;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractCommand;
import tr.edu.yildiz.ce.dap.appagent.criteria.CriteriaConstants;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.model.AppList;
import tr.edu.yildiz.ce.dap.appagent.model.Criteria;
import tr.edu.yildiz.ce.dap.appagent.model.CriteriaList;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.DeploymentProcess;

public class ListCommand extends AbstractCommand implements CriteriaConstants{
	

	public ListCommand(DeploymentProcess process) {
		super(process);
	}
	
	private boolean applyCriteria(Bundle bundle,CriteriaList criterias){
		for (Criteria c : criterias.getCriteria()) {
			if (!c.getName().equals(NAME.APP_NAME)){
				if (c.getOperator().equals(OPERATOR.EQUALS))
					if (!bundle.getSymbolicName().equals(c.getValue()))
						return false;
				if (c.getOperator().equals(OPERATOR.LIKE))
					if (!bundle.getSymbolicName().contains(c.getValue()))
						return false;
			}
			if (!c.getName().equals(NAME.APP_VERSION)){
				if (c.getOperator().equals(OPERATOR.EQUALS))
					if (!bundle.getVersion().toString().equals(c.getValue()))
						return false;
				if (c.getOperator().equals(OPERATOR.LIKE))
					if (!bundle.getVersion().toString().contains(c.getValue()))
						return false;
				if (c.getOperator().equals(OPERATOR.GREATER_THAN))
					if (bundle.getVersion().toString().compareTo(c.getValue())> 0)
						return false;
				if (c.getOperator().equals(OPERATOR.LESS_THAN))
					if (bundle.getVersion().toString().compareTo(c.getValue())< 0)
						return false;
			}
		}
		return true;
	}
	
	private App createApp(Bundle bundle){
		App app = new App();
		app.setName(bundle.getSymbolicName());
		app.setVersion(bundle.getVersion().toString());
		return app;
	}
	
	private AppList getAppList(CriteriaList criterias){
		AppList appList = new AppList();
		Bundle[] bundles = getProcess().getProcessManager().getContext().getBundles();
		for (Bundle bundle : bundles) {
			if (applyCriteria(bundle, criterias))
				appList.getApp().add(createApp(bundle));
		}
		return appList;
	}
	

	@Override
	public DapMessage execute(DapMessage msg) throws BasicAgentException {
		DapMessage retMsg = new DapMessage();
		retMsg.setAppList(getAppList(msg.getCriteriaList()));
		return retMsg;
	}

	@Override
	public DapMessage rollback(DapMessage msg) throws BasicAgentException {
		DapMessage retMsg = new DapMessage();
		return retMsg;
	}

}
